package com.promise.jokerdream.work.custom

import com.promise.jokerdream.database.entity.TaskGroupConfigEntity
import com.promise.jokerdream.database.entity.TaskConfigEntity
import com.promise.jokerdream.database.UserDataManager
import com.promise.jokerdream.network.HttpApiConstants
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.repository.PhoneGameApi
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult
import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.utils.AppContext
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import kotlinx.coroutines.Dispatchers

/**
 * 自定义任务工作
 * 负责按顺序执行任务组中的所有任务
 */
class CustomTaskWork(
    private val taskGroupConfig: TaskGroupConfigEntity,
    uin: String,
    private val userDataManager: UserDataManager
) : BaseWork(uin) {

    override val name: String = taskGroupConfig.groupName
    override val priority: Int = 5 // 中等优先级
    override val isActWork: Boolean = false // 自定义任务通常不是活动类工作

    private val gameApi = GameApi.getInstance()
    private val phoneGameApi = PhoneGameApi.getInstance()
    
    // 历史记录管理器
    private val historyManager by lazy { 
        ExecutionHistoryManager.getInstance(AppContext.get()) 
    }

    override suspend fun executeWork(): WorkResult {
        return try {
            // 从数据库加载任务列表
            val taskList = withContext(Dispatchers.IO) {
                userDataManager.getTasksByGroupId(taskGroupConfig.groupId)
            }
            
            // 按顺序执行任务组中的每个任务
            taskList.forEachIndexed { taskIndex, taskConfig ->
                // 只执行启用的任务
                if (!taskConfig.enabled) {
                    return@forEachIndexed
                }
                
                // 执行指定次数的任务
                repeat(taskConfig.executionCount) { executionIndex ->
                    
                    val result = executeSingleTask(taskConfig)
                    when (result) {
                        is WorkResult.Success -> {
                            val successMessage = "第 ${executionIndex + 1} 次执行成功"
                            println(successMessage)
                            historyManager.addHistory(taskConfig.taskName, successMessage)
                        }
                        is WorkResult.Failure -> {
                            val failureMessage = "第 ${executionIndex + 1} 次执行失败: ${result.message}"
                            println(failureMessage)
                            historyManager.addHistory(taskConfig.taskName, failureMessage)
                        }
                        is WorkResult.Cancelled -> {
                        }
                    }
                    
                    // 每次执行后稍作延迟，避免请求过于频繁
                    if (executionIndex < taskConfig.executionCount - 1) {
                        delay(100) // 100ms延迟
                    }
                }
            }
            WorkResult.Success
            
        } catch (e: Exception) {
            val errorMessage = "执行异常: ${taskGroupConfig.groupName}, 错误: ${e.message}"
            println(errorMessage)
            historyManager.addHistory(name, errorMessage)
            WorkResult.Failure(e, "执行失败: ${e.message}")
        }
    }

    /**
     * 执行单次任务
     */
    private suspend fun executeSingleTask(taskConfig: TaskConfigEntity): WorkResult {
        // 首先验证URL是否有效
        val urlType = validateUrl(taskConfig.taskLink)
        
        val result = when (urlType) {
            UrlType.PHONE -> {
                // 使用手机端API
                phoneGameApi.queryXmlData(taskConfig.taskLink)
            }
            UrlType.PC -> {
                // 使用PC端API，传入uin参数
                gameApi.queryRawData(taskConfig.taskLink, uin)
            }
            UrlType.INVALID -> {
                // 这种情况已经在上面处理了，但为了完整性
                throw Exception("任务链接异常")
            }
        }
        
        return result.fold(
            onSuccess = { response ->
                WorkResult.Success
            },
            onFailure = { exception ->
                WorkResult.Failure(exception, exception.message)
            }
        )
    }

    /**
     * URL类型枚举
     */
    private enum class UrlType {
        PC,      // PC端URL
        PHONE,   // 手机端URL
        INVALID  // 无效URL
    }

    /**
     * 验证URL类型
     * @param url 要验证的URL
     * @return URL类型
     */
    private fun validateUrl(url: String): UrlType {
        return when {
            isPhoneApiUrl(url) -> UrlType.PHONE
            isPcApiUrl(url) -> UrlType.PC
            else -> UrlType.INVALID
        }
    }

    /**
     * 判断是否为手机端API URL
     */
    private fun isPhoneApiUrl(url: String): Boolean {
        return url.startsWith(HttpApiConstants.PhoneUrls.main)
    }

    /**
     * 判断是否为PC端API URL
     */
    private fun isPcApiUrl(url: String): Boolean {
        return url.startsWith(HttpApiConstants.PcUrls.main)
    }
}
